//
//  CPHomeMoreTypeView.swift
//  cockpit
//
//  Created by Haijun Si on 2020/7/9.
//  Copyright © 2020 chenganrt. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import NSObject_Rx

class CPHomeMoreTypeView: UIView {
    
    var dataArray:[CPHomeMoreTypeModel]? {
        didSet {
            if let dataArr = dataArray ,dataArr.count > 0 {
                self.viewHeight = CGFloat(dataArray!.count/4 + 1) * CPScreenWidth/4.0
                self.refreshUI()
            }
        }
    }
    
    var btnClick:PublishSubject = PublishSubject<CPHomeMoreTypeModel>()
    
    private let btnWidth = CPScreenWidth/4.0
    
    private var viewHeight:CGFloat?
    
    private func setViewUI() {
        if let dataArr = dataArray {
            for (index,model) in dataArr.enumerated() {
                let btn = UIButton.init(type: UIButton.ButtonType.custom)
                btn.frame = CGRect(x: CGFloat((index % 4)) * btnWidth, y: CGFloat((index / 4)) * btnWidth, width: btnWidth, height: btnWidth)
                btn.tag = index
                btn.setTitle(model.btnName, for: UIControl.State.normal)
                btn.setTitleColor(CPColor666, for: UIControl.State.normal)
                btn.setImage(UIImage.init(named: model.btnImg ?? HOME_BTN_IMAGE), for: UIControl.State.normal)
                btn.setImgAddTextMethod()
                
                btn.rx.tap
                .subscribe(onNext: { [weak self] in
                    toast(text: "名称==\(model.btnName ?? ""),类型==\(model.btnType ?? "")")
                    self?.btnClick.onNext(model)
                })
                    .disposed(by: rx.disposeBag)
                self.addSubview(btn)
            }
        }
    }
    
    public func getViewHeight() -> CGFloat {
        return self.viewHeight ?? CPScreenWidth/4.0
    }
    
    private func refreshUI() {
        self.childRemoveSubView()
        self.setViewUI()
    }
    
    override init(frame: CGRect) {
        super.init(frame:frame)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}
